package com.qdairlines.service.user.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qdairlines.dao.user.PermissionMapper;
import com.qdairlines.entity.user.Permission;
import com.qdairlines.entity.user.RolePermission;
import com.qdairlines.service.base.impl.BaseServiceImpl;
import com.qdairlines.service.user.PermissionService;
import com.qdairlines.service.user.RolePermissionService;

@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission,Integer>  implements PermissionService {

	@Autowired
	private PermissionMapper permissionMapper;
	@Autowired
	private RolePermissionService rolePermissionService;

	@Autowired
	public void setBaseMapper() {
		super.setBaseMapper(permissionMapper);
	}

	@Override
	public List<Permission> listPermissionByWorkcode(String workcode) {
		return permissionMapper.selectPermissionByWorkcode(workcode);
	}

	@Override
	public List<String> listPermissionCodeByWorkcode(String workcode) {
		List<Permission> list = this.listPermissionByWorkcode(workcode);
		if(list !=null && list.size()>0){
			List<String> listPermission = new ArrayList<String>();
			for(Permission p : list){
				listPermission.add(p.getPermissionCode());
			}
			return listPermission;
		}
		return null;
	}

	@Override
	public List<Permission> listPermissionByRoleCode(String roleCode) {
		return permissionMapper.selectPermissionByRoleCode(roleCode);
	}


	@Override
	public Permission getPermissionByCode(String permissionCode) {
		Permission permission = new Permission();
		permission.setPermissionCode(permissionCode);
		List<Permission> list = this.listData(permission);
		if(list !=null && list.size() ==1){
			return list.get(0);
		}else{
			return null;
		}
	}
	
	@Override
	public Permission getPermissionByName(String permissionName) {
		Permission permission = new Permission();
		permission.setPermissionName(permissionName);
		List<Permission> list = this.listData(permission);
		if(list !=null && list.size() ==1){
			return list.get(0);
		}else{
			return null;
		}
	}
	
	@Override
	@Transactional
	public int  deleteByPrimaryKey(Integer id){
		RolePermission rp = new RolePermission();
		rp.setPermissionId(id);
		List<RolePermission> list = rolePermissionService.listData(rp);
		if(list !=null && list.size()>0){
			for(RolePermission p : list){
				rolePermissionService.deleteByPrimaryKey(p.getId());
			}
		}
		permissionMapper.deleteByPrimaryKey(id);
		return 1;
	}

}
